//
//  main.m
//  01Study
//
//  Created by AbstractLee on 2020/7/8.
//  Copyright © 2020 Test. All rights reserved.
//

#import <Foundation/Foundation.h>

typedef struct Books {
    // ARC中NSString是强类型，不能通过手动释放，但是C中结构体会被手动释放或者自动释放，释放之前就要对成员进行释放
    // strong类型引用计数不能是0， 所以不能被释放
    // __unsafe_unretained 表示这个变量不会被retain，引用计数不会加1
    __unsafe_unretained NSString *title;
    int book_id;
} Book;

// 声明一个Person类
@interface Person : NSObject {

@protected
    // 姓名
    NSString *name;
    // 年龄
    NSNumber *age;
    // 朋友们
    NSMutableArray *friendNames;
    // 看的书
    Book book;
@public
    NSString *Name;
}

// 名字属性
@property (readonly) NSString *nameProperty;

// init
- (Person *)init:(NSString *)initName :(NSNumber *)initAge;

// sayPerson
- (void)sayPerson;

// 添加一个朋友
- (void)addFriend:(NSString *)friendName;

// 去除一个朋友
- (void)removeFriend:(NSString *)friendName withError:(NSError **)error;

@end

// 实现
@implementation Person
// init
- (Person *)init:(NSString *)initName :(NSNumber *)initAge {
    if (self = [super init]) {
        name = initName;
        age = initAge;
        friendNames = [[NSMutableArray alloc] init];
        book.book_id = 0;
        book.title = @"Objective-C 从入门到放弃";
        _nameProperty = name;
    }
    return self;
}

- (void)sayPerson {
    NSLog(@"姓名：%@ 年龄：%@", name, age);
    if (friendNames.count > 0) {
        NSString *friends = [[NSString alloc] init];
        friends = [friends stringByAppendingString:@"朋友们："];
        for (NSString *friendName in friendNames) {
            friends = [friends stringByAppendingFormat:@"%@，", friendName];
        }
        NSLog(@"%@", friends);
    }
    NSLog(@"看的书：%@", book.title);
}

- (void)addFriend:(NSString *)friendName {
    [friendNames addObject:friendName];
}

- (void)removeFriend:(NSString *)friendName withError :(NSError **)error {
    if (![friendNames containsObject:friendName]) {
        *error = [NSError errorWithDomain:@"com.test.study" code:-1 userInfo:(id) @"没有这个朋友啊"];
        return;
    }
    [friendNames removeObject:friendName];
}

@end


int main(int argc, const char *argv[]) {
    // 自动释放池
    @autoreleasepool {
        // 先调用 alloc 申请内存，然后调用init初始化一个Person *对象
        Person *person = [[Person alloc] init:@"Bob" :@24];
        [person sayPerson];
        [person addFriend:@"Lee"];
        [person sayPerson];
        NSError *error = nil;
        [person removeFriend:@"Lee" withError:&error];
//        if(error) {
//            NSLog(@"%@", error.userInfo);
//        }
//        [person removeFriend:@"Lee" withError:&error];
//        if(error) {
//            NSLog(@"%@", error.userInfo);
//        }
//        [person sayPerson];
    }
    return 0;
}
